#!/usr/bin/env python3
from socketserver import TCPServer,BaseRequestHandler
from time import time,sleep
from threading import Thread
import socket
from repeator.repeator import repeat
from multiprocessing import  Process

clist = {}
def clear_proc():
    global clist
    while True:
        sleep(50)
        t = time()
        keys=[]
        for k in clist.keys():
            keys.append(k)
        for k in keys:
            if t-clist[k][1]>10:
                item = clist.pop(k)
                try:
                    item[0].shutdown(socket.SHUT_RDWR)
                    item[0].close()
                except Exception as e:
                    print(str(e))
def repeat_proc(sock1,sock2):
    try:
        repeat( sock1.fileno(), sock2.fileno() )
        #break out while
        sock1.close()
        sock2.close()
    except Exception as e:
        pass
#__main__
def proxy():
    global clist
    socks = socket.socket()
    socks.setsockopt(socket.SOL_SOCKET , socket.SO_REUSEADDR,1)
    socks.bind( ('0.0.0.0',8001) )
    clear_t = Thread(target=clear_proc)
    clear_t.start()
    socks.listen(2)
    t1=None
    while True:
        res=socks.accept()
        sock = res[0]
        if sock==None:
            continue
        sha1 = sock.recv(41)
        if len(sha1)==0:
            sock.close()
            continue
        client = clist.get( sha1 )
        if client is None:
            clist[ sha1 ] = ( sock, time() )
        else:
            pair = (client[0], sock)
            clist.pop( sha1 )
            reply = '----------------------ok\n'.encode('utf8')
            pair[0].send(reply)
            pair[1].send(reply)
            t1 = Process(target=repeat_proc, args=(pair[0], pair[1]) )
            t1.start()
        
if __name__=='__main__':
    proxy()
